﻿using System.Reflection;

namespace CodeBackup.FrmGrid
{

    public delegate void HeadCheckboxstatueHandle(bool statue);
    internal class FGrid
    {
        private Form form;
        private DataGridView dataGrid;

        /// <summary>
        /// 全選點擊事件
        /// </summary>
        public event HeadCheckboxstatueHandle onclickCheckedChanged;

        /// <summary>
        /// 初始化完成后
        /// </summary>
        public event EventHandler initGridCompleted;


        protected virtual void HeadCheckstatue(bool statue)
        {
            onclickCheckedChanged?.Invoke(statue);
        }

        protected virtual void GridCompleted(object sender, EventArgs e)
        {
            dataGrid.Invoke(() =>
            {
                initGridCompleted?.Invoke(sender, e);
            });
        }


        public FGrid(Form form, DataGridView dataGrid)
        {
            this.form = form;
            this.dataGrid = dataGrid;
            this.form.FormClosing += Form_FormClosing;
            ((System.ComponentModel.ISupportInitialize)dataGrid).BeginInit();
            typeof(DataGridView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, dataGrid, new object[] { true });
            ///不設置 datamember首次會觸發兩次complete事件，一次就重置datameber一次是加載數據
            //this.dataGrid.DataMember = "cbs";
            this.dataGrid.DataBindingComplete += DataGrid_DataBindingComplete;

            DataGridViewCellStyle dataGridViewCellStyle1 = new DataGridViewCellStyle();
            DataGridViewCellStyle dataGridViewCellStyle2 = new DataGridViewCellStyle();
            DataGridViewCellStyle dataGridViewCellStyle3 = new DataGridViewCellStyle();

            dataGrid.AllowUserToAddRows = false;
            dataGrid.AllowUserToDeleteRows = false;
            dataGridViewCellStyle1.BackColor = Color.FromArgb(238, 239, 249);
            dataGrid.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
            dataGrid.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
            dataGrid.BackgroundColor = Color.White;
            dataGridViewCellStyle2.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dataGridViewCellStyle2.BackColor = SystemColors.Control;
            dataGridViewCellStyle2.Font = new Font("細明體", 12F, FontStyle.Regular, GraphicsUnit.Point);
            dataGridViewCellStyle2.ForeColor = Color.WhiteSmoke;
            dataGridViewCellStyle2.SelectionBackColor = SystemColors.Highlight;
            dataGridViewCellStyle2.SelectionForeColor = SystemColors.HighlightText;
            dataGridViewCellStyle2.WrapMode = DataGridViewTriState.True;
            dataGrid.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2;
            dataGrid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
            dataGrid.ColumnHeadersHeight = 35;
            dataGridViewCellStyle3.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dataGridViewCellStyle3.BackColor = SystemColors.Window;
            dataGridViewCellStyle3.Font = new Font("細明體", 12F, FontStyle.Regular, GraphicsUnit.Point);
            dataGridViewCellStyle3.ForeColor = SystemColors.ControlText;
            dataGridViewCellStyle3.SelectionBackColor = Color.FromArgb(123, 150, 221);
            dataGridViewCellStyle3.SelectionForeColor = SystemColors.HighlightText;
            dataGridViewCellStyle3.WrapMode = DataGridViewTriState.False;
            dataGrid.DefaultCellStyle = dataGridViewCellStyle3;
            dataGrid.RowTemplate.Height = 28;
            dataGrid.RowTemplate.Resizable = DataGridViewTriState.False;
            dataGrid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGrid.RowHeadersWidth = 25;
            dataGrid.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            ((System.ComponentModel.ISupportInitialize)dataGrid).EndInit();
        }

        private void DataGrid_DataBindingComplete(object? sender, DataGridViewBindingCompleteEventArgs e)
        {
            //if (dataGrid.DataSource == null || dataGrid.Rows.Count == 0)
            //{
            //    MessageBox.Show("查無資料！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //}
        }

        public void initGrid(object[] args=null)
        {

            dataGrid.AutoGenerateColumns = false;
            Task.Run(() =>
            {
                try
                {
                    ((System.ComponentModel.ISupportInitialize)dataGrid).BeginInit();


                    IGrid grid = null;
  

                   
                    if (args == null)
                    {
                        grid = GridFactory.GetGrid(this.form.GetType().Name);
                    }
                    else
                    {
                        grid = GridFactory.GetGrid(this.form.GetType().Name, args);
                    }

                    

                    List<DataGridViewColumn> datas = new List<DataGridViewColumn>();
                    bool hasCheckboxItem = false;
                    grid.Columns.ForEach(gridColumn =>
                    {
                        DataGridViewColumn column;
                        if (gridColumn.RowType.Contains("DataGridViewTextBox"))
                        {
                            column = new DataGridViewTextBoxColumn();
                            column.Width = gridColumn.Width;
                        }
                        else if (gridColumn.RowType.Contains("DataGridViewCheckBox"))
                        {
                            column = new DataGridViewCheckBoxColumn();
                            column.Resizable = DataGridViewTriState.False;
                            hasCheckboxItem = true;
                            column.Width = 100;
                        }
                        else
                        {
                            column = new DataGridViewColumn();
                            column.Width = gridColumn.Width;
                        }


                        column.HeaderText = gridColumn.HeaderText;
                        column.Visible = gridColumn.Visible;
                        column.DataPropertyName = gridColumn.DataPropertyName;
                        column.Frozen = gridColumn.Frozen;
                        column.ReadOnly = gridColumn.Readonly;
                        
                        datas.Add(column);

                    });

                    if (dataGrid.InvokeRequired)
                    {
                        dataGrid.BeginInvoke(delegate
                        {
               
                            dataGrid.Columns.AddRange(datas.ToArray());
                            
                        });
                    }
                    else
                    {

                        dataGrid.Columns.AddRange(datas.ToArray());
                    }

                    if (hasCheckboxItem) { AddHeadCheckBox(); }

                }
                finally
                {
                    GridCompleted(dataGrid, new EventArgs());
                    ((System.ComponentModel.ISupportInitialize)dataGrid).EndInit();
                }

            });


        }

        /// <summary>
        /// 是否開啓統計
        /// </summary>
        private bool sum = false;

        public bool EnableSum
        {
            set
            {

                if (sum != value)
                {
                    onEnableSumChange(value);
                }
                sum = value;
            }
        }



        private void onEnableSumChange(bool value)
        {

            if (value) { CreateSumControl(); }
        }

        /// <summary>
        /// 縂記錄數
        /// </summary>
        private ToolStripStatusLabel itemcount;
        /// <summary>
        /// 選中總計
        /// </summary>
        private ToolStripStatusLabel itemselectcount;

        void Update_itemcount(int count)
        {

            itemcount.Text = $"總筆數：{count}";

        }

        void Update_itemselectcount(int count)
        {
            itemselectcount.Text = $"選取筆數：{count}";
        }

        void CreateSumControl()
        {
            StatusStrip statusStrip = null;
            foreach (Control control in form.Controls)
            {
                if (control is StatusStrip)
                {
                    statusStrip = (StatusStrip)control;
                    break;
                }
            }
            if (statusStrip == null) return;


            itemcount = new ToolStripStatusLabel();
            itemselectcount = new ToolStripStatusLabel();

            // 
            // toolslable_itemcount
            // 
            itemcount.BorderSides = ToolStripStatusLabelBorderSides.Left;
            itemcount.Font = new Font("細明體", 12F, FontStyle.Bold, GraphicsUnit.Point);
            itemcount.ForeColor = Color.Purple;
            itemcount.Name = "auto_itemcount";
            itemcount.Padding = new Padding(10, 0, 10, 0);
            itemcount.Size = new Size(117, 20);
            itemcount.Text = "總筆數：00";
            // 
            // toolStripStatusLabel4
            // 
            itemselectcount.AutoSize = false;
            itemselectcount.BorderSides = ToolStripStatusLabelBorderSides.Left;
            itemselectcount.Font = new Font("細明體", 12F, FontStyle.Bold, GraphicsUnit.Point);
            itemselectcount.ForeColor = Color.Purple;
            itemselectcount.Name = "auto_itemselectcount";
            itemselectcount.Padding = new Padding(10, 0, 10, 0);
            itemselectcount.Size = new Size(150, 20);
            itemselectcount.Text = "選取筆數：0";
            statusStrip.SuspendLayout();
            statusStrip.Items.Add(itemcount);
            statusStrip.Items.Add(itemselectcount);

            statusStrip.ResumeLayout(false);
            statusStrip.PerformLayout();
            dataGrid.DataBindingComplete += DataGrid_DataBindingCompleteSum;
            dataGrid.CellContentClick += DataGrid_CellContentClick;
            onclickCheckedChanged += EdiGrid_onclickCheckedChanged; ;
        }

        private void EdiGrid_onclickCheckedChanged(bool statue)
        {
            if (statue)
            {
                if (dataGrid == null) return;
                Update_itemselectcount(dataGrid.Rows.Count);
            }
            else
            {
                Update_itemselectcount(0);
            }
        }

        private async void DataGrid_CellContentClick(object? sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex != 0) return;
            dataGrid.EndEdit();
            int count = 0;
            await Task.Run(() =>
            {
                foreach (DataGridViewRow row in dataGrid.Rows)
                {
                    DataGridViewCheckBoxCell checkBoxCell = row.Cells[0] as DataGridViewCheckBoxCell;
                    if (checkBoxCell == null || checkBoxCell.Value == null || !(bool)checkBoxCell.Value) continue;
                    count++;
                }
            });
            Update_itemselectcount(count);
        }

        private void DataGrid_DataBindingCompleteSum(object? sender, DataGridViewBindingCompleteEventArgs e)
        {
            Update_itemcount(dataGrid.Rows.Count);
        }

        private void AddHeadCheckBox()
        {
            // 添加全选复选框到头部
            CheckBox headerCheckBox = new CheckBox();
            headerCheckBox.Size = new Size(15, 15);
            headerCheckBox.CheckedChanged += (sender, e) => ToggleAllSelection(dataGrid, headerCheckBox.Checked);

            if (dataGrid.InvokeRequired)
            {
                dataGrid.BeginInvoke(delegate
                {
                    dataGrid.Controls.Add(headerCheckBox);
                });
            }
            else
            {
                dataGrid.Controls.Add(headerCheckBox);
            }

            dataGrid.CellPainting += (sender, e) =>
            {
                if (e.ColumnIndex == 0 && e.RowIndex == -1)
                {
                    // 绘制全选复选框

                    e.PaintBackground(e.ClipBounds, true);
                    headerCheckBox.Location = new Point(e.CellBounds.Location.X + 43, e.CellBounds.Location.Y + 12);
                    headerCheckBox.Show();
                    e.Handled = true;
                }
            };
        }
        private void Form_FormClosing(object? sender, FormClosingEventArgs e)
        {

        }


        private bool IsAllSelected(DataGridView dataGridView)
        {
            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                DataGridViewCheckBoxCell checkBoxCell = row.Cells[0] as DataGridViewCheckBoxCell;
                if (checkBoxCell.Value == null) return false;
                if (checkBoxCell == null || !(bool)checkBoxCell.Value)
                {
                    return false;
                }
            }
            return true;
        }

        private void ToggleAllSelection(DataGridView dataGridView, bool @checked)
        {
            dataGridView.EndEdit();
            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                DataGridViewCheckBoxCell checkBoxCell = row.Cells[0] as DataGridViewCheckBoxCell;
                checkBoxCell.Value = @checked;
            }
            HeadCheckstatue(@checked);
        }
    }
}
